package cn.com.open.opensaas.scoreservice.service.impl;

import cn.com.open.opensaas.scoreservice.common.QuestionConstant;
import cn.com.open.opensaas.scoreservice.domain.TestPaperModel.SectionCount;
import cn.com.open.opensaas.scoreservice.domain.TestPaperModel.TestPaperContent;
import cn.com.open.opensaas.scoreservice.mapper.TestPaperContentMapper;
import cn.com.open.opensaas.scoreservice.service.PaperContentService;
import cn.com.open.opensaas.scoreservice.service.QuestionContentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("paperContentService")
public class PaperContentServiceImpl implements PaperContentService {

    @Autowired
    private TestPaperContentMapper testPaperContentMapper;
    @Autowired
    private QuestionContentService questionContentService;

    /**
     * 根据Id获取TestPaperContent
     *
     * @param paperId
     * @return
     */
    @Override
    public TestPaperContent findTestPaperById(String paperId) {
        return testPaperContentMapper.findTestPaperById(paperId);
    }

    /**
     * 试卷判分逻辑
     *
     * @param questionList 学生作答结果
     * @param paperContent 标准答案数据
     * @return
     */
    @Override
    public Map<String, Object> judge(List<Map<String, Object>> questionList, Map<String, Object> paperContent) {
        //存储最终返回结果
        Map<String, Object> resultMap = new HashMap<>();
        //存储试卷总分
        Double totalScore = 0.0;
        //用来存储Data关键值中的数据
        Map<String, Object> dataMap = new HashMap<>();
        //用来存储Data中Items关键值中的数据
        List<Map<String, Object>> itemList = new ArrayList<>();
        //用来存储Data中Stat关键值中的数据
        List<Map<String, Object>> statList = new ArrayList<>();

        //获取paperContent中section集合
        List<Map<String, Object>> sections = (List<Map<String, Object>>) paperContent.get("Sections");
        //获取paperContent中items集合
        List<Map<String, Object>> items = (List<Map<String, Object>>) paperContent.get("Items");

        //创建section统计模型
        SectionCount sectionCount = new SectionCount();

        //循环paperContent中sections集合
        for (Map<String, Object> section : sections) {
            //获取每个section的itemID集合
            List<String> itemIds = (List<String>) section.get("ItemID");
            //将section中Identifier,Title及itemID数量存入sectionCount模型对应属性
            sectionCount.setQuestionTypeId((String) section.get("Identifier"));
            sectionCount.setQuestionTypeName((String) section.get("Title"));
            sectionCount.setItemSize(itemIds.size());

            //循环itemID集合获取section统计信息及itemList
            loopItemIDs(itemIds, items, sectionCount, questionList, itemList);

            //将每个section分值记入试卷总分
            totalScore += sectionCount.getSectionScore();
            //将statMap存入statList
            statList.add(sectionCount.getStatMap());
        }
        //存储dataMap数据
        dataMap.put("TotalScore", totalScore);
        dataMap.put("Items", itemList);
        dataMap.put("Stat", statList);
        //存储resultMap数据
        resultMap.put("Data", dataMap);
        resultMap.put("Code", 0);
        resultMap.put("Message", "");

        return resultMap;
    }

    /**
     * 查询所有数据  用于测试用例
     * @return
     */
    @Override
    public TestPaperContent findAll() {
        return testPaperContentMapper.findAll().get(0);
    }

    /**
     * 循环itemID集合获取section统计信息及itemList
     *
     * @param itemIds section下的itemID集合
     * @param items   paperContent下的items集合
     * @return
     * @Param sectionCount section统计模型
     * @Param questionList 学生答案集合
     * @Param itemList 用于返回的itemList
     */
    private void loopItemIDs(List<String> itemIds, List<Map<String, Object>> items, SectionCount sectionCount, List<Map<String, Object>> questionList, List<Map<String, Object>> itemList) {
        //重置correctCount=0,wrongCount=0,unAnswerCount=0,sectionScore=0.0
        sectionCount.resetSectionCount();
        //循环section下的itemID集合
        for (String itemId : itemIds) {
            //循环item集合通过itemId在items中对sectionCount及itemList进行赋值
            loopItems(itemId, items, questionList, sectionCount, itemList);
        }
    }

    /**
     * 循环item集合通过itemId在items中对sectionCount及itemList进行赋值
     *
     * @param itemId
     * @param items
     * @return
     * @Param questionList 学生答案集合
     * @Param sectionCount section统计模型
     * @Param itemList 用于赋值的itemList
     */
    private void loopItems(String itemId, List<Map<String, Object>> items, List<Map<String, Object>> questionList, SectionCount sectionCount, List<Map<String, Object>> itemList) {
        //批量获取数据库中对应学生答案试题数据
        List<Map<String, Object>> dbQuestionList = questionContentService.batchFindDbQuestion(questionList);

        //循环每个items中I1为itemId的item
        for (Map<String, Object> item : items) {
            if (itemId.equals(item.get(QuestionConstant.ITEM_IDENTIFIER))) {
                //循环Question对item添加I15属性
                loopQuestion(item, questionList, sectionCount);
                String contentJson = null;
                //循环DB试题List,向contentJson赋值
                for (Map<String, Object> dbQuestion : dbQuestionList) {
                    if ((dbQuestion.get("questionId").toString().toLowerCase()).equals(item.get(QuestionConstant.ITEM_IDENTIFIER))) {
                        contentJson = (String) dbQuestion.get("contentJson");
                        break;
                    }
                }

                //对item进行判分
                Map<String, Object> map = questionContentService.judgeQuestion(item, contentJson);

                //获取单题判分结果
                Map<String, Object> itemMap = (Map<String, Object>) map.get("itemMap");
                //获取单题得分
                Double score = (Double) itemMap.get(QuestionConstant.STUDENT_ANSWER_SCORE);
                //当前题的总分
                Double itemScore = Double.parseDouble(item.get(QuestionConstant.ITEM_SCORE) + "");
                if(score != -1) {
                    if (score == 0.0 && !sectionCount.getUnAnswerFlag()) {//score为0.0 并且flag为做答状态（=false）且试题不含Sub
                        //统计错误
                        sectionCount.setWrongCount(1);
                    } else if (!sectionCount.getUnAnswerFlag()) {
                        //有子试题的试题，得分小于题总分视为错误
                        if (score < itemScore && item.get(QuestionConstant.STUDENT_ANSWER) == null) {
                            //统计错误
                            sectionCount.setWrongCount(1);
                        } else {
                            //统计正确
                            sectionCount.setCorrectCount(1);
                        }
                    }
                    //记入sectionScore
                    sectionCount.setSectionScore(score);
                }
                //将itemMap存入itemList中
                itemList.add(itemMap);
                break;
            }
        }
    }

    /**
     * 循环Question对item添加I15或Sub属性
     *
     * @param item
     * @param questionList
     * @return
     * @Param sectionCount
     */
    private void loopQuestion(Map<String, Object> item, List<Map<String, Object>> questionList, SectionCount sectionCount) {
        //重置未做答标记为false
        sectionCount.setUnAnswerFlag(false);
        List answers = new ArrayList<String>();
        //循环questionList获取I1为itemId的question,将I15添加到item中
        for (Map<String, Object> question : questionList) {
            if (item.get(QuestionConstant.ITEM_IDENTIFIER).equals(question.get(QuestionConstant.ITEM_IDENTIFIER))) {//I1一致
                //获取学生答案集合
                List<Map<String, Object>> subList = null;
                for (Map.Entry<String, Object> qmap : question.entrySet()) {
                    if (qmap.getKey().equalsIgnoreCase(QuestionConstant.SUB_ITEMS)) {
                        subList = (List<Map<String, Object>>) qmap.getValue();
                    }
                }

                if (subList == null || subList.isEmpty()) {//学生传递的数据有子集(有I15)
                    answers = (List) question.get(QuestionConstant.STUDENT_ANSWER);
                    //将答案添加到item中
                    item.put(QuestionConstant.STUDENT_ANSWER, answers);
                } else {//学生传递数据有子试题
                    //循环子试题填充answers用以判断是否未做答
                    for (Map<String, Object> sub : subList) {
                        if (sub.get(QuestionConstant.STUDENT_ANSWER) != null) {
                            answers.add(sub.get(QuestionConstant.STUDENT_ANSWER));
                        }
                    }
                    //将子试题答案添加到item中
                    item.put(QuestionConstant.SUB_ITEMS, subList);
                }
                break;
            }
        }
        //答案为空或数量为0，视为未做答
        if (answers == null || answers.isEmpty()) {
            //统计未做答
            sectionCount.setUnAnswerCount(1);
            //修改未做答状态为已做答 true
            sectionCount.setUnAnswerFlag(true);
        }
    }
}